var PI = Math.PI;
var util = require('util');
var fs = require('fs');
var path = require('path');
var zipeUtil = require('./zipUtil.js');
var fileUtil = require('./fileUtil.js');
var EventEmitter = require('events').EventEmitter;
var fileutil_jqf = require("./lib/file-util.js");
var async = require("async");

exports.building_war = function(option, callback) {
	console.log('war.building_war');
	// var event = new EventEmitter();
	// event.on('some_event1', unzipDa);
	// event.on('some_event2', fileUtil.copy);
	// setTimeout(function() {
	// 	event.emit('some_event1');
	// 	event.emit('some_event2',path.join(__dirname, "..", "resource", "war"), path.join(__dirname, "..", "resource", "buildresult", "war"), function(err,data){});
	// 	// event.emit('some_event', path.join(__dirname, "..", "resource", "war"), path.join(__dirname, "..", "resource", "buildresult", "war"), function(err,data){});
	// }, 1000);
    var da_path = option.da_path;
    var servletVersion = option.servletVersion;
    var warName = option.warName;
	var dnaVersion = null;
	var resourcePath = path.join(__dirname, "..", "resource");
	var buildPath = option.buildPath;
	//var da_path = path.join(resourcePath, "dna-bap-3.7.SP.M8(pub).da");
	var unzip_da_path = path.join(buildPath, "unzip");
	var warSourcePath = path.join(resourcePath, "war");
	var warTargetPath = path.join(buildPath, "war");
	if (null == servletVersion) {
		servletVersion = 3.0;
	}
	if (null == warName) {
		warName = "test";
	}
	console.log("war包名称：", warName);
	console.log("servlet版本是：", servletVersion);
	//解压da包
	unzipDa(da_path, unzip_da_path, function(err, data) {
		var flag = setInterval(function() {
			//获取dna版本号
			dnaVersion = getDnaVersionSync(path.join(unzip_da_path, "product.info"));
			if (null != dnaVersion) {
				console.log(dnaVersion);
				option.dnaVersion = dnaVersion;
				//复制war包
				fileutil_jqf.copySeq(warSourcePath, warTargetPath, function() {
					console.log("0．拷贝war包成功");
					console.time('parallel');
					async.parallel({
						one: function(done) {
							//1．在WEB-INF的lib目录下拷入com.jiuqi.dna.core.proxy.jar；
							fileutil_jqf.copySeq(path.join(resourcePath, "plugins", "lib", dnaVersion), path.join(warTargetPath, "WEB-INF", "lib"), function(err, data) {
								done(null, "在WEB-INF的lib目录下拷入com.jiuqi.dna.core.proxy.jar");
							});
						},
						two: function(done) {
							//2．将dna目录下所有内容拷贝到WEB-INF/eclipse/plugins/dna下；删除WEB-INF/eclipse/plugins/dna下，core目录中的com.jiuqi.dna.core.jetty
							fileutil_jqf.copySeq(path.join(unzip_da_path, "dna"), path.join(warTargetPath, "WEB-INF", "eclipse", "plugins", "dna"), function(err, data) {
								var coreDir = path.join(warTargetPath, "WEB-INF", "eclipse", "plugins", "dna", "core");
								fs.readdir(coreDir, function(err, files) {
									files.forEach(function(item) {
										if (item.indexOf("com.jiuqi.dna.core.jetty") > -1) {
											fs.unlink(path.join(coreDir, item), function(err, data) {
												var message = "将dna目录下所有内容拷贝到WEB-INF/eclipse/plugins/dna下;" +
													"删除文件：" + path.join(coreDir, item);
												done(null, message);
											});
										}
									});
								});
							});

						},
						three: function(done) {
							// 3．将da包目录下的lib目录拷贝到WEB-INF/eclipse/plugins/dna/lib下；
							fileutil_jqf.copySeq(path.join(unzip_da_path, "lib"), path.join(warTargetPath, "WEB-INF", "eclipse", "plugins", "dna", "lib"), function(err, data) {
								done(null, "将da包目录下的lib目录拷贝到WEB-INF/eclipse/plugins/dna/lib下");
							});

						},
						four: function(done) {
							//4．将da包目录下的thr目录拷贝到WEB-INF/eclipse/plugins/dna/thr下;
							copyThr(unzip_da_path, warTargetPath, servletVersion, function() {
								done(null, '处理thr目录完成');
							});

						},
						five: function(done) {
							//5 将da包目录下的app目录下的内容拷贝到WEB-INF\eclipse\plugins\app下
							fileutil_jqf.copySeq(path.join(unzip_da_path, "app"), path.join(warTargetPath, "WEB-INF", "eclipse", "plugins", "app"), function(err, data) {
								if (err) {
									done(null, err);
								} else {
									done(null, "将da包目录下的app目录下的内容拷贝到WEB-INF/eclipse/plugins/app下");
								}
							});
						},
						six: function(done) {
							// 6．将da包对应的com.jiuqi.dna.core.bridge拷贝到WEB-INF/eclipse/plugins/dna/core下；
							fileutil_jqf.copySeq(path.join(resourcePath, "plugins", "core", dnaVersion), path.join(warTargetPath, "WEB-INF", "eclipse", "plugins", "dna", "core"), function(err, data) {
								done(null, "将da包对应的com.jiuqi.dna.core.bridge拷贝到WEB-INF/eclipse/plugins/dna/core下");
							});
						},
						seven: function(done) {
							// 7.修改web.xml中display-name
							updateXML(path.join(warTargetPath, "WEB-INF", "web.xml"), path.join(warTargetPath, "WEB-INF", "web.xml"), warName, function(err, data) {
								//console.log(fs.readFileSync(path.join(warTargetPath, "WEB-INF", "web.xml"), "utf-8"));
								done(null, "修改web.xml中display-name为" + warName + "成功");
							});
						},
					}, function(error, result) {
						console.log('1:', result.one);
						console.log('2:', result.two);
						console.log('3:', result.three);
						console.log('4:', result.four);
						console.log('5:', result.five);
						console.log('6:', result.six);
						console.log('7:', result.seven);
						console.timeEnd('parallel');
						var sourcePath = path.join(buildPath, "war");
						var targetPath = path.join(buildPath, warName + ".war");
						zipeUtil.zip(sourcePath, targetPath, function(err, data) {
							if (null != callback && typeof callback == "function") {
								callback();
							}
						});
					});
				});
				clearInterval(flag);
			}
		}, 200);
	});
};

exports.zip = function(req, res) {
	var sourcePath = path.join(__dirname, "..", "resource", "unzip");
	var targetPath = path.join(__dirname, "..", "resource", "buildresult", "result.zip");
	zipeUtil.zip(sourcePath, targetPath, function(err, data) {

	});
	res.end(util.inspect({
		"success": true
	}));
};

function getDnaVersionSync(filePath) {
	try {
		var data = fs.readFileSync(filePath, "utf-8");
		var DOMParser = require('xmldom').DOMParser;
		var doc = new DOMParser().parseFromString(data);
		var root = doc.documentElement;
		var childNodes = root.childNodes;
		for (var i = 0; i < childNodes.length; i++) {
			var node = childNodes[i];
			if (null != node.attributes && "project" == node.nodeName && "DNA" == node.getAttributeNode('id').value) {
				return node.getAttributeNode('version').value;
			}
		}
	} catch (e) {
		//console.log(e);
		return null;
	}

}

function updateXML(xmlPath, targetXmlPath, warName, callback) {
	var xmldom = require('xmldom');
	var XMLSerializer = require('xmldom').XMLSerializer;
	var DOMParser = require('xmldom').DOMParser;
	var data = fs.readFileSync(xmlPath, "utf-8");
	var doc = new DOMParser().parseFromString(data);
	var root = doc.documentElement;
	var childNodes = root.childNodes;
	for (var i = 0; i < childNodes.length; i++) {
		var node = childNodes[i];
		if ("display-name" == node.nodeName) {
			node.childNodes[0].nodeValue = warName;
			node.childNodes[0].data = warName;
			break;
		}
	}
	var xmldomresult = new XMLSerializer().serializeToString(doc);
	// 创建读取流
	// var readable = fs.createReadStream(xmldomresult);
	// 创建写入流
	var writable = fs.createWriteStream(targetXmlPath);
	writable.end(xmldomresult, function(err, data) {
		callback();
	});
	// 通过管道来传输流
	// readable.pipe(writable);
}

function copyThr(unzip_da_path, warTargetPath, servletVersion, callback) {
	fileutil_jqf.copySeq(path.join(unzip_da_path, "thr"), path.join(warTargetPath, "WEB-INF", "eclipse", "plugins", "dna", "thr"), function(err, data) {
		console.time('series');
		var async = require('async');
		var thrDir = path.join(warTargetPath, "WEB-INF", "eclipse", "plugins", "dna", "thr");
		async.series({
			one: function(done) {
				//删除thr目录中的javax.servlet、org.eclipse.jetty和org.eclipse.jetty.ajp,如果servletVersion <= 2.5,删除javax.servlet.jsp
				fs.readdir(thrDir, function(err, files) {
					files.forEach(function(item) {
						var name1 = item.split("-")[0];
						var name2 = item.split("_")[0];
						if (servletVersion <= 2.5) {
							if (name1 == "javax.servlet.jsp" || name2 == "javax.servlet.jsp") {
								fs.unlinkSync(path.join(thrDir, item));
								console.log("删除文件：" + path.join(thrDir, item));
							}
						}
						if (name1 == "javax.servlet" || name2 == "javax.servlet") {
							fs.unlinkSync(path.join(thrDir, item));
							console.log("删除文件：" + path.join(thrDir, item));
						} else if (name1 == "org.eclipse.jetty" || name2 == "org.eclipse.jetty") {
							fs.unlinkSync(path.join(thrDir, item));
							console.log("删除文件：" + path.join(thrDir, item));
						} else if (name1 == "org.eclipse.jetty.ajp" || name2 == "org.eclipse.jetty.ajp") {
							fs.unlinkSync(path.join(thrDir, item));
							console.log("删除文件：" + path.join(thrDir, item));
						}
					});
					done(null, "删除thr目录中的javax.servlet、org.eclipse.jetty和org.eclipse.jetty.ajp,如果servletVersion <= 2.5,删除javax.servlet.jsp");
				});
			},
			two: function(done) {
				//获取中间件中使用的javax.servlet的版本，如果是2.5及其以下，用与javax.servlet版本对应的javax.servlet.jsp替换WEB-INF/eclipse/plugins/dna/thr中的javax.servlet.jsp包
				if (servletVersion <= 2.5) {
					// 拷贝新的进去
					var jspDir = path.join(__dirname, "..", "resource", "jsp2.0");
					fs.readdir(jspDir, function(err, files) {
						files.forEach(function(item) {
							fs.createReadStream(path.join(jspDir, item)).pipe(fs.createWriteStream(path.join(thrDir, item))).on('finish', function() {
								done(null, "中间件支持的servlet版本是：" + servletVersion + "拷贝新的javax.servlet.jsp，文件名称是：" + item);
							});
						});
					});
				} else {
					done(null, "中间件支持的servlet版本是：" + servletVersion + " 无需替换");
				}
				//done('error info', null) //如果返回错误信息,//下面的流程控制将会被中断,直接跳到最后结果函数
			}
		}, function(error, result) {
			console.log('(1):', result.one);
			console.log('(2):', result.two);
			console.timeEnd('series');
			callback();
		})
	});
}

function unzipApp(appDir, callback) {
	var Count = function() {
		var num = 0;
		this.up = function() {
			num++;
			console.log(num);
		};
		this.down = function() {
			num--;
			console.log(num);
			if (num == 0) {
				callback();
			}
		};
	};
	fs.readdir(appDir, function(err, files) {
		var count = new Count();
		files.forEach(function(item) {
			var appPath = path.join(appDir, item);
			var stat = fs.lstatSync(appPath);
			if (!stat.isDirectory()) {
				var suffixName = path.extname(appPath); //后缀名
				if (".app" == suffixName) {
					count.up();
					zipeUtil.unzip(appPath, path.join(appDir, path.basename(appPath, ".app")), function(err, data) {
						fs.unlink(appPath, function(err, data) {
							console.log("删除文件：" + appPath);
							count.down();
						});
					});
				}
			}
		});
	});
}

function unzipDa(da_path, outputPath, callback) {
	zipeUtil.unzip(da_path, outputPath, function(err, data) {
		//解压da包中app目录下的.app文件，并删除.app文件 ,首先判断app目录是否存在，存在则解压
		var appDir = path.join(outputPath, "app");
		fs.exists(appDir, function(exist) {
			if (exist) {
				unzipApp(appDir, callback);
			} else {
				console.log("没有" + appDir);
				if (null != callback && typeof callback == "function") {
					callback();
				}

			}
		});
	});

};